/*
 * @Author: yuki
 * @Date: 2025-10-25 23:11:48
 * @LastEditTime: 2025-11-01 23:33:00
 * @Description: 公共逻辑
 */
import type { ArgumentMetadata } from '@nestjs/common';
import { BadRequestException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import type { ValidationError } from 'class-validator';
import { validate } from 'class-validator';

export async function handleError<T>(
  metadata: ArgumentMetadata,
  value: T,
  customHandleError?: (error: ValidationError[]) => any
) {
  const errorMessages = await validate(
    plainToInstance(metadata.metatype!, value)
  );
  if (errorMessages.length > 0) {
    if (customHandleError) {
      return customHandleError(errorMessages);
    } else {
      // 取第一个错误信息
      const error = errorMessages[0].constraints as Record<string, string>;
      const keys = Object.keys(error);
      throw new BadRequestException(error[keys[0]]);
    }
  }
}
